from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import CustomUser, Institution, Laboratory


@admin.register(Institution)
class InstitutionAdmin(admin.ModelAdmin):
    list_display = ['code', 'name', 'created_at']
    search_fields = ['code', 'name']
    list_filter = ['created_at']


@admin.register(Laboratory)
class LaboratoryAdmin(admin.ModelAdmin):
    list_display = ['code', 'name', 'institution', 'created_at']
    search_fields = ['code', 'name', 'institution__name']
    list_filter = ['institution', 'created_at']


@admin.register(CustomUser)
class CustomUserAdmin(UserAdmin):
    list_display = ['email', 'username', 'full_name', 'get_user_type_display', 'institution', 'laboratory', 'is_active', 'created_at']
    list_filter = ['is_active', 'is_staff', 'user_type', 'institution', 'laboratory', 'created_at']
    search_fields = ['email', 'username', 'full_name', 'phone']
    
    def get_user_type_display(self, obj):
        """显示用户类型的中文名称"""
        return obj.get_user_type_display()
    get_user_type_display.short_description = '用户类型'
    
    # 保持自定义fieldsets，但保留Django默认的密码处理方式
    fieldsets = (
        (None, {'fields': ('username', 'password')}),
        ('个人信息', {'fields': ('email', 'full_name', 'phone')}),
        ('权限', {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}),
        ('重要日期', {'fields': ('last_login', 'date_joined')}),
        ('扩展信息', {'fields': ('user_type', 'institution', 'laboratory')}),
    )
    
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('username', 'email', 'password1', 'password2'),
        }),
        ('个人信息', {'fields': ('full_name', 'phone')}),
        ('扩展信息', {'fields': ('user_type', 'institution', 'laboratory')}),
    )
    
    # 保持只读字段
    readonly_fields = ('last_login', 'date_joined')